package init

import (
	"bytes"
	"context"
	"encoding/json"
	"github.com/elastic/go-elasticsearch/v7"
	"github.com/elastic/go-elasticsearch/v7/esapi"
	"log"
	"strconv"
	"sync"
	"user_srv/basic/config"
	"user_srv/handler/models"
)

func InitEs() {
	var err error
	cfg := elasticsearch.Config{
		Addresses: []string{
			"http://14.103.175.197:9200",
		},
	}
	config.Es, err = elasticsearch.NewClient(cfg)
	if err != nil {
		panic("es init failed")
	} else {
		log.Println("es init success")
	}
}
func SyncEs() {
	var reserviton models.Reservation
	list, _ := reserviton.ReservationList()

	var wg sync.WaitGroup
	for _, rlist := range list {
		wg.Add(1)

		go func(reserviton *models.Reservation) {
			defer wg.Done()

			// Build the request body.
			data, err := json.Marshal(rlist)
			if err != nil {
				log.Fatalf("Error marshaling document: %s", err)
			}

			// Set up the request object.
			req := esapi.IndexRequest{
				Index:      "rlist",
				DocumentID: strconv.Itoa(int(rlist.Id)),
				Body:       bytes.NewReader(data),
				Refresh:    "true",
			}

			// Perform the request with the client.
			res, err := req.Do(context.Background(), config.Es)
			if err != nil {
				log.Fatalf("Error getting response: %s", err)
			}
			defer res.Body.Close()

		}(rlist)
	}
	wg.Wait()
}
